/**
 * 健康目标API接口
 * 封装所有健康目标相关操作
 */

const request = require('./request');

/**
 * 获取健康目标列表
 * @returns {Promise} 健康目标列表
 */
function getTargets() {
  return request.get('/health/targets');
}

/**
 * 更新健康目标
 * @param {Object} data - 健康目标数据
 * @returns {Promise} 更新结果
 */
function updateTarget(data) {
  return request.put('/health/target', data);
}

/**
 * 获取用户健康信息
 * @returns {Promise} 用户健康信息
 */
function getUserHealthInfo() {
  // 模拟接口返回
  return new Promise((resolve) => {
    // 从本地存储获取用户健康信息
    const healthInfo = wx.getStorageSync('userHealthInfo');
    
    // 如果本地有缓存用户健康信息，直接返回
    if (healthInfo) {
      resolve(healthInfo);
    } else {
      // 返回默认用户健康信息
      const defaultHealthInfo = {
        // 风险等级： 0=低风险, 1=中风险, 2=高风险
        riskLevel: 0,
        // 最新血糖记录
        latestGlucose: 5.6,
        latestGlucoseTime: '今天 08:30',
        // 血糖目标范围
        glucoseTargetMin: 3.9,
        glucoseTargetMax: 7.2,
        // 最新血压记录
        latestSystolic: 120,
        latestDiastolic: 80,
        latestBpTime: '今天 08:30',
        // 血压目标范围
        bpTargetSystolicMin: 90,
        bpTargetSystolicMax: 140,
        bpTargetDiastolicMin: 60,
        bpTargetDiastolicMax: 90,
        // 最新体重记录
        latestWeight: 65.5,
        latestWeightTime: '今天 08:30',
        // 体重目标范围
        weightTarget: 65.0,
        weightTargetMin: 60.0,
        weightTargetMax: 70.0,
        // 每日推荐摄入量
        dailyCaloriesTarget: 2000,
        dailyWaterTarget: 2000,
        dailyProteinTarget: 60,
        dailyCarbTarget: 250,
        dailyFatTarget: 60,
        // 运动目标
        dailyStepsTarget: 8000,
        weeklyExerciseMinutes: 150
      };
      
      // 保存到本地存储
      wx.setStorageSync('userHealthInfo', defaultHealthInfo);
      resolve(defaultHealthInfo);
    }
  });
}

/**
 * 更新用户健康信息
 * @param {Object} healthInfo - 健康信息
 * @returns {Promise} 更新结果
 */
function updateUserHealthInfo(healthInfo) {
  return new Promise((resolve) => {
    // 获取当前存储的健康信息
    const currentHealthInfo = wx.getStorageSync('userHealthInfo') || {};
    
    // 合并更新信息
    const updatedHealthInfo = { ...currentHealthInfo, ...healthInfo };
    
    // 保存到本地存储
    wx.setStorageSync('userHealthInfo', updatedHealthInfo);
    
    // 模拟成功返回
    resolve({ success: true, message: '健康信息更新成功' });
  });
}

/**
 * 获取健康目标建议
 * 根据用户信息和分类生成个性化健康目标建议
 * @param {Object} userInfo - 用户信息
 * @param {Object} classifications - 用户分类信息
 * @returns {Promise} 健康目标建议
 */
function getHealthTargetSuggestions(userInfo, classifications) {
  return new Promise((resolve) => {
    // 初始化建议对象
    const suggestions = {
      glucose: {},
      bloodPressure: {},
      weight: {},
      diet: {},
      exercise: {}
    };
    
    // 根据用户信息计算BMI
    const heightInMeters = userInfo.height / 100;
    const bmi = userInfo.weight / (heightInMeters * heightInMeters);
    
    // 计算理想体重范围
    const idealWeight = 22 * heightInMeters * heightInMeters;
    const weightLowerBound = Math.floor(idealWeight - 5);
    const weightUpperBound = Math.ceil(idealWeight + 5);
    
    // 设置体重建议
    suggestions.weight = {
      target: Math.round(idealWeight * 10) / 10,
      min: weightLowerBound,
      max: weightUpperBound,
      message: `基于您的身高(${userInfo.height}cm)，理想体重范围为${weightLowerBound}~${weightUpperBound}kg`
    };
    
    // 根据用户分类设置血糖目标
    if (classifications.hasDiabetes) {
      suggestions.glucose = {
        fasting: { min: 3.9, max: 7.2 },
        afterMeal: { min: 3.9, max: 10.0 },
        message: '糖尿病患者建议空腹血糖控制在3.9~7.2mmol/L，餐后血糖控制在3.9~10.0mmol/L'
      };
    } else {
      suggestions.glucose = {
        fasting: { min: 3.9, max: 6.1 },
        afterMeal: { min: 3.9, max: 7.8 },
        message: '健康人群建议空腹血糖控制在3.9~6.1mmol/L，餐后血糖控制在3.9~7.8mmol/L'
      };
    }
    
    // 根据用户分类设置血压目标
    if (classifications.hasHypertension) {
      suggestions.bloodPressure = {
        systolic: { min: 90, max: 140 },
        diastolic: { min: 60, max: 90 },
        message: '高血压患者建议血压控制在140/90mmHg以下'
      };
    } else if (classifications.isElderly) {
      suggestions.bloodPressure = {
        systolic: { min: 90, max: 150 },
        diastolic: { min: 60, max: 90 },
        message: '老年人建议血压控制在150/90mmHg以下'
      };
    } else {
      suggestions.bloodPressure = {
        systolic: { min: 90, max: 120 },
        diastolic: { min: 60, max: 80 },
        message: '健康人群理想血压为120/80mmHg以下'
      };
    }
    
    // 设置饮食建议
    const baseCalories = userInfo.gender === 1 ? 2000 : 1800;
    let adjustedCalories = baseCalories;
    
    // 根据BMI调整热量
    if (bmi > 24) {
      adjustedCalories = Math.round(baseCalories * 0.9);
    } else if (bmi < 18.5) {
      adjustedCalories = Math.round(baseCalories * 1.1);
    }
    
    suggestions.diet = {
      calories: adjustedCalories,
      protein: Math.round(adjustedCalories * 0.15 / 4), // 15% 蛋白质，1g=4卡路里
      carbs: Math.round(adjustedCalories * 0.55 / 4),   // 55% 碳水，1g=4卡路里
      fat: Math.round(adjustedCalories * 0.3 / 9),      // 30% 脂肪，1g=9卡路里
      water: userInfo.gender === 1 ? 2000 : 1800,        // 每日饮水量(ml)
      message: `根据您的情况，建议每日摄入${adjustedCalories}卡路里`
    };
    
    // 设置运动建议
    let stepsTarget = 8000;
    let exerciseMinutes = 150; // 每周运动时间(分钟)
    
    if (classifications.isElderly) {
      stepsTarget = 6000;
      exerciseMinutes = 120;
    } else if (bmi > 24) {
      stepsTarget = 10000;
      exerciseMinutes = 180;
    }
    
    suggestions.exercise = {
      steps: stepsTarget,
      minutes: exerciseMinutes,
      message: `建议每日步行${stepsTarget}步，每周至少进行${exerciseMinutes}分钟中等强度运动`
    };
    
    resolve(suggestions);
  });
}

/**
 * 分析健康风险
 * 根据用户信息和历史数据评估健康风险
 * @param {Object} userInfo - 用户信息
 * @param {Object} classifications - 用户分类信息
 * @param {Array} recentRecords - 最近的健康记录
 * @returns {Promise} 健康风险评估结果
 */
function analyzeHealthRisk(userInfo, classifications, recentRecords) {
  return new Promise((resolve) => {
    // 初始化风险评估
    const riskAssessment = {
      level: 0, // 0=低风险, 1=中风险, 2=高风险
      factors: [],
      suggestions: []
    };
    
    // 风险因素计数
    let riskFactors = 0;
    
    // 计算BMI并评估风险
    const heightInMeters = userInfo.height / 100;
    const bmi = userInfo.weight / (heightInMeters * heightInMeters);
    
    if (bmi >= 28) {
      riskFactors += 2;
      riskAssessment.factors.push('肥胖 (BMI≥28)');
      riskAssessment.suggestions.push('控制饮食，增加运动，逐步降低体重至健康范围');
    } else if (bmi >= 24) {
      riskFactors += 1;
      riskAssessment.factors.push('超重 (24≤BMI<28)');
      riskAssessment.suggestions.push('控制饮食，保持适当运动，维持健康体重');
    }
    
    // 评估疾病风险
    if (classifications.hasDiabetes) {
      riskFactors += 2;
      riskAssessment.factors.push('糖尿病');
      riskAssessment.suggestions.push('定期监测血糖，严格遵医嘱服药，保持健康生活方式');
    }
    
    if (classifications.hasHypertension) {
      riskFactors += 2;
      riskAssessment.factors.push('高血压');
      riskAssessment.suggestions.push('控制血压，减少盐分摄入，避免剧烈运动');
    }
    
    // 评估特殊人群风险
    if (classifications.isPregnant) {
      riskFactors += 1;
      riskAssessment.factors.push('孕期');
      riskAssessment.suggestions.push('定期孕检，均衡饮食，适当运动');
    }
    
    if (classifications.isElderly) {
      riskFactors += 1;
      riskAssessment.factors.push('老年');
      riskAssessment.suggestions.push('定期体检，保持适度运动，预防跌倒');
    }
    
    // 根据风险因素设置风险等级
    if (riskFactors >= 3) {
      riskAssessment.level = 2; // 高风险
    } else if (riskFactors >= 1) {
      riskAssessment.level = 1; // 中风险
    } else {
      riskAssessment.level = 0; // 低风险
      riskAssessment.factors.push('无明显风险因素');
      riskAssessment.suggestions.push('保持健康生活方式，定期体检');
    }
    
    resolve(riskAssessment);
  });
}

// 导出模块
module.exports = {
  getTargets,
  updateTarget,
  getUserHealthInfo,
  updateUserHealthInfo,
  getHealthTargetSuggestions,
  analyzeHealthRisk
}; 